package com.wang.transfer.util.springBean;

import com.wang.transfer.util.springBean.annotation.Mapper;
import com.wang.transfer.util.springBean.annotation.Res;
import com.wang.transfer.util.springBean.beanConfig.BeanFactory;
import com.wang.transfer.util.springBean.dao.UserDao;
import com.wang.transfer.util.springBean.exception.ResponseProcessor;
import com.wang.transfer.util.springBean.resolver.CommonResolver;
import com.wang.transfer.util.springBean.util.SpringUtils;

import java.util.Scanner;

@Mapper
public class ApiTest {

//    @Res(name = "use")
//    UserDaoImpl userDaoImpl;

    @Res(name = "userDao")
    UserDao userDao;

    static BeanFactory beanFactory;

    private static final String OPERATION_EXIT = "EXIT";

    public ApiTest() {
        // 这里会出错，原因：类的加载顺序的问题，导致还没有在beanFactory中加入userDao时就在执行这里的方法。
//        this.userDao = (UserDao) beanFactory.beanRegister.getSingletonBean("userDao");
//        this.userDao.queryUser();
//        System.out.println(this.userDao.getClass().getClassLoader());
    }

    public static void main(String[] args) {

        // 1.创建bean工厂（同时完成了加载资源、创建注册单例bean注册器的操作）
        beanFactory = new BeanFactory();

        /*// 2.第一次获取bean（通过 反射创建bean，缓存bean）
        UserDao userDao = (UserDao) beanFactory.getBean("userDao");
        System.out.println(userDao);
        userDao.queryUser();

        // 3.第二次获取bean（从缓存中获取bean）
        UserDao userDao1 = (UserDao) beanFactory.getBean("userDao");
        System.out.println(userDao1);
        userDao1.queryUser();*/

        new CommonResolver(beanFactory);

        ApiTest apiTest = (ApiTest) beanFactory.getBean(SpringUtils.beanNameFormat(ApiTest.class));
        apiTest.userDao.queryUser();

        ApiTest apiTest1 = (ApiTest) beanFactory.getBean(SpringUtils.beanNameFormat(ApiTest.class));
        apiTest1.userDao.queryUser();


        // 测试：ResponseProcessor，范式理解
        String handle = ResponseProcessor.handle(apiTest, "123", "responseProcessor.handle", req -> {
            if (req.userDao != null) {
                return "123";
            }
            return "456";
        });

        /*
          程序保持持续运行
         */
        System.out.println("请开始您的输入，EXIT/E 退出");
        Scanner scan = new Scanner(System.in);
        while(scan.hasNext()) {
            String in = scan.next();
            if(OPERATION_EXIT.equalsIgnoreCase(in)
                    || OPERATION_EXIT.substring(0, 1).equalsIgnoreCase(in)) {
                System.out.println("您已成功退出！");
                break;
            }
            System.out.println("您输入的值："+in);
        }
    }
}
